//
//  HAJSBridgeHandlerEvent.m
//  HAFund
//
//  Created by 夏成龙 on 2018/11/12.
//  Copyright © 2018年 夏成龙. All rights reserved.
//

#import "HAJSBridgeHandlerEvent.h"
#import "HAJSBridgeHandlerEventMethod.h"

@implementation HAJSEvent

- (instancetype)initWithEventParmas:(NSDictionary *)eventParmas {
    if ([super init]) {
        _methodName = eventParmas[@"methodName"];
        _callBackName = eventParmas[@"callBackName"];
        _params = eventParmas[@"params"];
        _timestamp = [eventParmas[@"timestamp"] longLongValue];
    }
    return self;
}

@end

@interface HAJSBridgeHandlerEvent ()

/// 交互方法实现类
@property (strong, nonatomic) HAJSBridgeHandlerEventMethod *eventMethod;

@end

@implementation HAJSBridgeHandlerEvent

- (void)bridgeResponseEvnetWithEvnet:(HAJSEvent *)event {
    if (!event) {
        return;
    }
    if (!event.methodName) {
        return;
    }
    [self signatureMessageWithEvent:event];
}

- (void)callBackFunctionWithEvnet:(HAJSEvent *)event params:(nonnull NSDictionary *)params {
    if (event.callBackName.length <= 0) {
        return;
    }
    NSString *jsString = @"";
    if (params) {
        NSData *data = [NSJSONSerialization dataWithJSONObject:params options:NSJSONWritingPrettyPrinted error:nil];
        NSString *paramsString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
        jsString = [NSString stringWithFormat:@"WebViewJavascriptBridge.callBackMessage(%@, %@)", event.callBackName, paramsString];
    } else {
        jsString = [NSString stringWithFormat:@"WebViewJavascriptBridge.callBackMessage(%@, "")", event.callBackName];
    }
    [event.handler evaluateJavaScriptWithMethodName:jsString params:nil completionHandler:^(id  _Nonnull result, NSError * _Nonnull error) {
        NSLog(@"%@", result);
    }];
}

- (void)signatureMessageWithEvent:(HAJSEvent *)event {
    if (!event.methodName || event.methodName.length <= 0) {
        return;
    }
    NSString *methodNameString = [NSString stringWithFormat:@"%@:", event.methodName];
    SEL handlerMethod = NSSelectorFromString(methodNameString);
    if ([self.eventMethod respondsToSelector:handlerMethod]) {
        [self.eventMethod performSelector:handlerMethod withObject:event];
    } else {
        for (HAJSBridgeHandlerEventMethod *eventMethod in self.eventMethod.subObject) {
            if ([eventMethod respondsToSelector:handlerMethod]) {
                [eventMethod performSelector:handlerMethod withObject:event];
            }
        }
    }
}

@end
